package registry

import (
	"github.com/emicklei/go-restful"
	"kubeInstall/handlers"
	"kubeInstall/model/registry"
	"net/http"
	"strconv"
)

func ListRepositories(r *restful.Request, resp *restful.Response) {

	opts := new(registry.ListRepositoryOpts)
	projectName := r.PathParameter("project_name")
	opts.PageSize, _ = strconv.Atoi(r.QueryParameter("page_size"))
	opts.Page, _ = strconv.Atoi(r.QueryParameter("page"))

	projectDetails, err := registry.ListRepository(projectName, opts)

	if err != nil {
		handlers.RenderError(resp, "List registry Repository failed", http.StatusBadRequest)
		return
	}

	resp.WriteHeaderAndJson(http.StatusOK, projectDetails, restful.MIME_JSON)

}

func GetRepository(r *restful.Request, resp *restful.Response) {

	projectName := r.PathParameter("project_name")
	repositoryName := r.PathParameter("repository_name")

	projectDetails, err := registry.GetRepository(projectName, repositoryName)

	if err != nil {
		handlers.RenderError(resp, "get registry Repository failed", http.StatusBadRequest)
		return
	}

	resp.WriteHeaderAndJson(http.StatusOK, projectDetails, restful.MIME_JSON)
}

func UpdateRepository(r *restful.Request, resp *restful.Response) {
	projectName := r.PathParameter("project_name")
	repositoryName := r.PathParameter("repository_name")

	var opts registry.CreateRepositoryOpts

	if err := r.ReadEntity(&opts); err != nil {
		handlers.RenderError(resp, "update registry repository from request failed", http.StatusInternalServerError)
		return
	}

	err := registry.UpdateRepository(projectName, repositoryName, opts)

	if err != nil {
		handlers.RenderError(resp, err.Error(), http.StatusBadRequest)
		return
	}

	resp.WriteHeaderAndJson(http.StatusOK, "", restful.MIME_JSON)

}

func DeleteRepository(r *restful.Request, resp *restful.Response) {
	projectName := r.PathParameter("project_name")
	repositoryName := r.PathParameter("repository_name")

	err := registry.DeleteRepository(projectName, repositoryName)

	if err != nil {
		handlers.RenderError(resp, err.Error(), http.StatusBadRequest)
		return
	}

	resp.WriteHeaderAndJson(http.StatusOK, "", restful.MIME_JSON)
}
